package com.czwx.bee.base.web.aop;

import com.czwx.bee.base.common.dto.ResponseDto;
import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.common.exception.BusinessException;
import com.czwx.bee.base.common.utils.ResponseDtoFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author WIKI
 * @date 2016年11月12日 下午3:19:56
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 拦截业务异常
     *
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseDto notFount(BusinessException e) {

        System.out.println("BusinessException拦截异常");
        return new ResponseDto(BizExceptionEnum.SYSTEM_EEROR);
    }
    /**
     * 拦截未知的运行时异常
     *
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseDto notFount(RuntimeException e) {
        return  new ResponseDtoFactory().build(BizExceptionEnum.FAIL_OPERATION.getCode(),e.getMessage());
    }


    /**
     * 参数异常
     *
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseDto notFount(ConstraintViolationException e) {
        String mesg="";
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            mesg+=constraintViolation.getMessage()+" ";
        }

        return  new ResponseDto(BizExceptionEnum.FAIL_OPERATION.getCode(),mesg);
    }

    @ExceptionHandler(value = { MethodArgumentNotValidException.class })
    public ResponseDto handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String rs="";
        BindingResult result = e.getBindingResult();
        for (FieldError fieldError : result.getFieldErrors()) {
           rs+=fieldError.getDefaultMessage()+"";
        }
        return new ResponseDto(BizExceptionEnum.FAIL_OPERATION.getCode(), rs);
    }
}
